package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        if (categoryEntityList == null || categoryEntityList.size() == 0) {
            return new ArrayList<>();
        }
        return categoryEntityList.stream()
                .filter(x -> Long.valueOf(0L).equals(x.getParentCid()))
                .map(menu -> {
                    menu.setChildrenList(getChildrenList(menu, categoryEntityList));
                    return menu;
                })
                .sorted(Comparator.comparingInt(c -> (c.getSort()==null?0:c.getSort())))
                .collect(Collectors.toList());
    }

    private List<CategoryEntity> getChildrenList(CategoryEntity menu, List<CategoryEntity> all) {
        return all.stream()
                .filter(x -> menu.getCatId().equals(x.getParentCid()))
                .map(x1 -> {
                    x1.setChildrenList(getChildrenList(x1, all));
                    return x1;
                })
                .sorted(Comparator.comparingInt(c -> (c.getSort()==null?0:c.getSort())))
                .collect(Collectors.toList());
    }
}